package com.eshore.ezone.downloads;

import com.eshore.ezone.utils.IOUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public abstract class AbstractFileDownloader {
    protected File mFile;
    protected String mFilePath;//File cache path
    protected String mFileName;//File cache name
    
    public File getFile() {
        return mFile;
    }
    public void setFile(File file) {
        this.mFile = file;
    }
    public String getFilePath() {
        return mFilePath;
    }
    public void setFilePath(String filePath) {
        this.mFilePath = filePath;
    }
    public String getFileName() {
        return mFileName;
    }
    public void setFileName(String fileName) {
        this.mFileName = fileName;
    }
    
    protected abstract void loadConfigs();
    protected abstract InputStream downloadFile(String url);
    protected abstract boolean streamFile(InputStream in, FileOutputStream os);
    protected abstract void saveFile(String fileName) throws IOException;
    
    public boolean saveFile(InputStream in) throws IOException {
        mFile = new File(mFilePath+mFileName);
        FileOutputStream os = null;
        try {
            if(!mFile.exists())  {
                mFile.createNewFile(); 
            } 
            os = new FileOutputStream(mFile, true);
            return streamFile(in, os);
        } finally {
            IOUtils.closeStream(in);
            IOUtils.closeStream(os);
        }
    }
}
